<template>
  <div class="content-box">
    <div class="content">
      <div class="group">
        <div class="header">
          <div class="title">梯控组地图</div>
          <div class="handler">
            <div class="showCode">
              <el-switch v-model="showCode" style="--el-switch-on-color: #54bcbd" /><span class="showCodeLabel">显示编码</span>
            </div>
          </div>
        </div>
        <div class="tree">
          <ZTree
            ref="zTreeRef"
            :id="treeId"
            :api="getGroupTree"
            :params="{ rgFlag: 1 }"
            :show-code="showCode"
            :enableDrag="true"
            :checkNodeId="checkNodeId"
            @click-dom="zTreeOnClick"
            @add-hover-dom="addHoverDom"
            @remove-hover-dom="removeHoverDom"
            @on-drop="onDrop"
          />
        </div>
      </div>
      <div class="main">
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="梯控点列表"
            rowKey="doorsn"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
            v-if="columns.length"
          >
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
              <el-button type="primary" text :icon="CirclePlus" @click="dialogVisible1 = true">增加梯控点</el-button>
              <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
    </div>
    <DoorDialog :dialogVisible="dialogVisible1" :handleClose="handleClose" :submitCallback="_submitDoor" v-if="mapndx" />
  </div>
</template>

<script setup lang="tsx" name="electronMap">
/* eslint-disable */
// @ts-nocheck
import { ref, onMounted, nextTick } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ZTree from "@/components/ZTree/index.vue";
import RoomDrawer from "./components/DoorDialog.vue";
import DoorDialog from "./components/DoorDialog.vue";
import { CirclePlus, Delete } from "@element-plus/icons-vue";
import { getGroupTree } from "@/api/modules/common";
import {
  getGroupList,
  deleteGroup,
  addGroup,
  getAreaSelList,
  addGroupNode,
  delGroupNode,
  editGroupNode
} from "@/api/modules/elevatorControl/manage/electronGroup";
import { ElMessage, ElMessageBox, UploadRequestOptions } from "element-plus";

const zTreeRef = ref();
const treeId = ref("tree");
const showCode = ref(false);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const loading = ref(false);
const isDeleting = ref(false);
const areaSelList = ref([]);
const columns: any = ref([]);
const zNodes = ref([]);
const mapndx = ref("");
const curTreeNode = ref("");
const checkNodeId = ref("");

const proTable = ref();

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records,
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getGroupList({ ...newParams, rgId: mapndx.value });
};

const _submitDoor = async ids => {
  try {
    const res = await addGroup({
      doorSns: ids,
      rgIds: [mapndx.value],
      timezone: 0
    });
    const { v1, v2 } = res.data;
    ElMessage.success(`增加门禁成功${v1}, 失败${v2}`);
    dialogVisible1.value = false;
    proTable.value.clearSelection();
    proTable.value.reset();
  } catch (error) {
    console.log(error);
  }
};

const _batchDel = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择梯控点");
    return false;
  }
  ElMessageBox.confirm(`是否删除所选梯控点?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const res = await deleteGroup({ doorSns: selectedListIds, rgIds: [mapndx.value], timezone: 0 });
      const { v1, v2 } = res.data;
      ElMessage.success(`删除成功：${v1},失败：${v2}`);

      proTable.value.clearSelection();
      proTable.value.getTableList();
    } catch (error) {
      console.log(error);
    }
  });
};

/**
 * 关闭上传照片弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
};

const beforeCloseFunc = async (action, instance, done, cb) => {
  if (action === "confirm") {
    instance.confirmButtonLoading = true;
    cb && cb();
  } else {
    done();
  }
};

/**
 * 拖拽节点完成回调
 */
const onDrop = async ({ event, treeId, treeNodes, targetNode, moveType, isCopy, zNode, callback }) => {
  if (zNode.parentId === targetNode?.id || !targetNode) return;
  try {
    const res = await editGroupNode({
      rgfullname: treeNodes[0].name,
      rgid: treeNodes[0].id,
      parent: targetNode.id
    });
    checkNodeId.value = treeNodes[0].id;
    callback && callback();
    ElMessage.success("保存成功");
  } catch (error) {
    console.log(error);
  }
};

/**
 * 获取区域选择列表
 */
const getAreaSelData = async () => {
  try {
    const res = await getAreaSelList();
    areaSelList.value = res.data;
    areaSelList.value.unshift({
      key: "",
      value: "全部"
    });
    areaSelList.value = areaSelList.value.map(item => {
      return {
        label: item.value,
        value: item.key
      };
    });
  } catch (error) {
    console.log(error);
  }
};

/**
 * 点击树节点
 */
function zTreeOnClick({ treeNode }) {
  mapndx.value = "";
  nextTick(() => {
    mapndx.value = treeNode.id;
    proTable.value && proTable.value.getTableList();
  });
}

/**
 * 新增节点
 */
function addNode(treeNode) {
  const zTree = $.fn.zTree.getZTreeObj(treeId.value);
  ElMessageBox.prompt("请输入梯控组名称", "新增梯控组", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValidator: val => {
      if (!val) return false;
    },
    inputErrorMessage: "梯控组名称不能为空",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          const res = await addGroupNode({
            parent: treeNode.id,
            nlevel: treeNode.level + 1,
            rgflag: 1,
            acmode: 0,
            rgfullname: instance.inputValue
          });
          ElMessage.success("新增成功");
          const { rgfullname, rgid, acmode, nlevel, parent } = res.data;
          zTree.addNodes(treeNode, { id: rgid, pId: parent, name: rgfullname, no: rgid });
          const node = zTree.getNodeByParam("id", rgid);
          zTree.selectNode(node);
          $("#" + node.tId + "_a").click();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
}

/**
 * 删除节点
 */
function removeNode(treeNode) {
  if (!isDeleting.value) {
    useHandleData(delGroupNode, { id: treeNode.id }, `删除该梯控组`, "系统提示").then(() => {
      isDeleting.value = true;
      const zTree = $.fn.zTree.getZTreeObj(treeId.value);
      zTree.removeNode(treeNode, true);
      isDeleting.value = false;
      zTreeRef.value.refresh();
    });
    return false;
  } else {
    return true;
  }
}

/**
 * 修改节点
 */
function editNode(treeNode, zNode) {
  ElMessageBox.prompt("请输入梯控组名称", "修改梯控组", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: zNode.name,
    inputValidator: val => {
      if (!val) return false;
    },
    inputErrorMessage: "梯控组名称不能为空",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          const res = await editGroupNode({
            rgfullname: instance.inputValue,
            rgid: treeNode.id,
            parent: treeNode.parentId ?? zNode.parentId
          });
          ElMessage.success("修改成功");
          const zTree = $.fn.zTree.getZTreeObj(treeId.value);
          treeNode.name = instance.inputValue;
          zTree.updateNode(treeNode);
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
}

function addHoverDom({ treeId, treeNode, zNode }) {
  const sObj = $("#" + treeNode.tId + "_span");
  if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
  const addStr = "<span class='hoverBtn addBtn' id='addBtn_" + treeNode.tId + "' title='增加' onfocus='this.blur();'></span>";
  const editStr = "<span class='hoverBtn editBtn' id='editBtn_" + treeNode.tId + "' title='修改' onfocus='this.blur();'></span>";
  const removeStr =
    "<span class='hoverBtn removeBtn' id='removeBtn_" + treeNode.tId + "' title='删除' onfocus='this.blur();'></span>";
  const sObjItem = treeNode.parentId ? addStr + editStr + removeStr : addStr + editStr;
  sObj.after(sObjItem);
  const addBtn = $("#addBtn_" + treeNode.tId);
  const editBtn = $("#editBtn_" + treeNode.tId);
  const removeBtn = $("#removeBtn_" + treeNode.tId);
  if (addBtn)
    addBtn.bind("click", function () {
      addNode(treeNode);
      return false;
    });
  if (editBtn)
    editBtn.bind("click", function () {
      editNode(treeNode, zNode);
      return false;
    });
  if (removeBtn)
    removeBtn.bind("click", function () {
      removeNode(treeNode);
      return false;
    });
}

function removeHoverDom({ treeNode }) {
  $("#addBtn_" + treeNode.tId)
    .unbind()
    .remove();
  $("#editBtn_" + treeNode.tId)
    .unbind()
    .remove();
  $("#removeBtn_" + treeNode.tId)
    .unbind()
    .remove();
}

onMounted(() => {
  Promise.all([getAreaSelData()])
    .then(() => {
      columns.value = [
        { type: "selection", fixed: "left", width: 60 },
        {
          prop: "areaId",
          label: "区域",
          enum: areaSelList.value,
          search: { el: "select", defaultValue: "" },
          isShow: false
        },
        {
          prop: "clause",
          label: "描述",
          search: { el: "input" },
          isShow: false
        },
        {
          prop: "doorsn",
          label: "梯控点编号",
          minWidth: 200
        },
        {
          prop: "doorname",
          label: "描述",
          minWidth: 200
        }
        // {
        //   prop: "visitorflag",
        //   label: "是否通道",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         <el-checkbox disabled v-model={scope.row.visitorflag}></el-checkbox>
        //       </>
        //     );
        //   }
        // },
        // {
        //   prop: "enableflag",
        //   label: "启用",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         <el-checkbox disabled v-model={scope.row.enableflag}></el-checkbox>
        //       </>
        //     );
        //   }
        // }
      ];
    })
    .catch(error => {
      columns.value = [
        { type: "selection", fixed: "left", width: 60 },
        {
          prop: "doorsn",
          label: "梯控点编号",
          minWidth: 200
        },
        {
          prop: "doorname",
          label: "描述",
          minWidth: 200
        }
        // {
        //   prop: "visitorflag",
        //   label: "是否通道",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         <el-checkbox disabled v-model={scope.row.visitorflag}></el-checkbox>
        //       </>
        //     );
        //   }
        // },
        // {
        //   prop: "enableflag",
        //   label: "启用",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         <el-checkbox disabled v-model={scope.row.enableflag}></el-checkbox>
        //       </>
        //     );
        //   }
        // }
      ];
      console.log(error);
    });
});
</script>
<style lang="scss">
@import "./index.scss";
</style>
